package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.exceptions.BankException;
import com.acme.bankapp.exceptions.ClientExistsException;

public class BankService {

	static boolean addClient(Bank bank, Client client) throws IOException {
		
		try {
			bank.addClient(client);
			return true;
		} catch (ClientExistsException e) {
			System.out.println("Client already exist");
		}
		return false;
	}
	
	public static void modifyBank(Bank bank, Client client, int amount) throws BankException {
		client.getAccount().withdraw(amount);
	}
	
	public static void printBalance(Bank bank) {
		for (Client client : bank.getClients()) {
			System.out.println( client.getAccount().getBalance() );
		}
	}
	
	public static void printMaximumAmountToWithdraw(Bank bank) {
		for (Client client : bank.getClients()) {
			System.out.println( client.getAccount().maximumAmountToWithdraw() );
		}
	}
	
	public static void showBank(Bank bank){

		System.out.println("\nClients of " + bank.getName() + " :");
		System.out.println("-------------------");
		for (Client client : bank.getClients() ){
			System.out.println( client.getClientSalutation() );
		}
		System.out.println("-------------------");
		
	}
	
	public static void saveBank(Bank bank, File f) throws IOException{
		if (!f.exists()){
			f.createNewFile();
		}
		
		FileOutputStream fileStream = new FileOutputStream(f);
		ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
		
		objectStream.writeObject(bank);
		
		objectStream.close();
		fileStream.close();
	}
	
	public static Bank readBank(File f) throws IOException, ClassNotFoundException{
		
		if (!f.exists()){
			throw new IOException("DataBase is missing");
		}
		
		FileInputStream fileStream = new FileInputStream(f);
		ObjectInputStream objectStream = new ObjectInputStream(fileStream);
		
		Bank bank=null;
		Object restored = objectStream.readObject();
		if (restored instanceof Bank){ 
			bank = (Bank)restored; 
		}
		
		objectStream.close();
		fileStream.close();
		
		return bank;		
	}
}
